package com.hx.order.service.impl;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.hx.common.exception.CustomerException;
import com.hx.common.exception.MessageCode;
import com.hx.common.result.PageResult;
import com.hx.common.utils.SnowFlake;
import com.hx.order.dto.OrderDto;
import com.hx.order.mapper.OrderMapper;
import com.hx.order.pojo.Drug;
import com.hx.order.pojo.Order;
import com.hx.order.pojo.Subscribe;
import com.hx.order.service.DrugService;
import com.hx.order.service.OrderService;
import com.hx.order.service.SubscribeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private SubscribeService subscribeService;

    @Autowired
    private DrugService drugService;

    static int TYPE_RESERVE=1;
    static int TYPE_DRUG=2;
    /**
     * 返回全部记录
     * @return
     */
    public List<Order> findAll() {
        return orderMapper.selectAll();
    }

    /**
     * 分页查询
     * @param page 页码
     * @param size 每页记录数
     * @return 分页结果
     */
    public PageResult<Order> findPage(int page, int size) {
        PageHelper.startPage(page,size);
        Page<Order> orders = (Page<Order>) orderMapper.selectAll();
        return new PageResult<Order>(orders.getTotal(),orders.getResult());
    }

    /**
     * 条件查询
     * @param searchMap 查询条件
     * @return
     */
    public List<Order> findList(Map<String, Object> searchMap) {
        Example example = createExample(searchMap);
        return orderMapper.selectByExample(example);
    }

    /**
     * 分页+条件查询
     * @param searchMap
     * @param page
     * @param size
     * @return
     */
    public PageResult<Order> findPage(Map<String, Object> searchMap, int page, int size) {
        PageHelper.startPage(page,size);
        Example example = createExample(searchMap);
        Page<Order> orders = (Page<Order>) orderMapper.selectByExample(example);
        return new PageResult<Order>(orders.getTotal(),orders.getResult());
    }

    /**
     * 根据Id查询
     * @param
     * @return
     */
    public Order findById(String orderId) {
        return orderMapper.selectByPrimaryKey(orderId);
    }

    /**
     * 新增
     * @param order
     */
    public void add(Order order) {
        orderMapper.insert(order);
    }

    /**
     * 修改
     * @param order
     */
    public void update(Order order) {
        orderMapper.updateByPrimaryKeySelective(order);
    }

    /**
     *  删除
     * @param
     */
    public void delete(String orderId) {
        orderMapper.deleteByPrimaryKey(orderId);
    }

    @Override
    @Transactional
    public String createOrder(OrderDto orderDto) throws CustomerException {
        String orderId= SnowFlake.nextId()+"";
        Integer type = orderDto.getType();
        if(type > TYPE_RESERVE || StringUtils.isEmpty(type) || type<0){
            throw new CustomerException(MessageCode.NO_ORDER_TYPE);
        }
        if (type==TYPE_RESERVE){
            Long doctorId = orderDto.getDoctorId();
            Date dutyTime = orderDto.getDutyTime();
            Subscribe sub = subscribeService.findByDoctorId(doctorId,dutyTime);
            if (ObjectUtils.isEmpty(sub)){
                log.error("当前时间段该医生没有值班 sub:{}",sub);
                throw  new CustomerException(MessageCode.DOCTOR_TIME_NO);
            }
            //设置订单
            Order order=new Order();
            order.setOrderId(orderId);
            order.setTotalPay(sub.getPrice());
            order.setCreateTime(new Date());
            order.setDoctorId(orderDto.getDoctorId());
            order.setType(orderDto.getType());
            order.setUserId(orderDto.getUserId());
            orderMapper.insert(order);
            //减库存
            Subscribe subscribe=new Subscribe();
            if (sub.getNum()-1<0){
                throw new CustomerException(MessageCode.ORDER_IS_FULL);
            }
            subscribe.setNum(sub.getNum()-1);
            subscribe.setId(sub.getId());
            subscribeService.update(subscribe);
            Subscribe result = subscribeService.findById(sub.getId());
            int reservationNumber=result.getTotalNum()-result.getNum();
            log.info("当前预约号 num:{}",reservationNumber);
            return reservationNumber+"";
        }
        if (type==TYPE_DRUG){
            for(Long drugId:orderDto.getDrugIds()){
                Drug drug = drugService.findById(drugId);
                if (ObjectUtils.isEmpty(drug)){
                    log.error("下单的药品不存在，drugId:{}",drug);
                    throw new CustomerException(MessageCode.DRUG_IS_EMPTY);
                }

            }

        }
        return null;

    }

    @Override
    public List<Order> findAppointmentInformation(Long userId) {
        return orderMapper.findByUserId(userId);
    }


    /**
     * 构建查询条件
     * @param searchMap
     * @return
     */
    private Example createExample(Map<String, Object> searchMap){
        Example example=new Example(Order.class);
        Example.Criteria criteria = example.createCriteria();
        if(searchMap!=null){
            // 订单id
            if(searchMap.get("orderId")!=null && !"".equals(searchMap.get("orderId"))){
                criteria.andLike("orderId","%"+searchMap.get("orderId")+"%");
            }

            // type
            if(searchMap.get("type")!=null ){
                criteria.andEqualTo("type",searchMap.get("type"));
            }

        }
        return example;
    }



}
